"""
Case Type   : DATAVEC模块
Case Name   : enable_pq参数异常值设置验证
Create At   : 2025/4/10
Owner       : @peilinqian
Description :
    1、guc修改enable_pq为数字2
    2、guc修改enable_pq为字符test
    3、guc修改enable_pq为空
    4、alter system方式修改enable_pq为数字2
    5、修改postgresql.conf文件参数为空，重启数据库
    6、修改postgresql.conf文件参数为非法值，重启数据库
Expect      :
    1、guc修改enable_pq为数字2，修改失败
    2、guc修改enable_pq为字符test，修改失败
    3、guc修改enable_pq为空，修改失败
    4、alter system方式修改enable_pq为数字2，修改失败
    5、修改postgresql.conf文件参数为空，重启数据库，重启失败，报错相应行参数有问题
    6、修改postgresql.conf文件参数为非法值，重启数据库，重启失败，报错非法值
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

pri_dbuser = Node(node='PrimaryDbUser')
pq_lib_path = '/usr/local/sra_recall/lib/'
log = Logger()
log.info("----判断本地环境是否存在pq插件----")
check_cmd = f'if [ -d {pq_lib_path} ]; ' \
            f'then echo "True"; else echo "False"; fi'
log.info(check_cmd)
check_result = pri_dbuser.sh(check_cmd).result()
log.info(check_result)


@unittest.skipIf(check_result == 'False',
                 '----环境不具备PQ插件，跳过执行用例----')
class DataVecTestCase(unittest.TestCase):
    def setUp(self):
        log.info(f'----{os.path.basename(__file__)}:start----')
        self.sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.pq_env_name = 'DATAVEC_PQ_LIB_PATH'
        step_txt = '----step0:设置pq环境变量; expect:成功----'
        log.info(step_txt)
        check_env_cmd = f'if grep -q "{self.pq_env_name}" ' \
                        f'"{macro.DB_ENV_PATH}"; ' \
                        f'then echo "True" ; else echo "False" ;fi'
        log.info(check_env_cmd)
        check_env_result = pri_dbuser.sh(check_env_cmd).result()
        log.info(check_env_result)
        if check_env_result == 'False':
            results = []
            log.info('--设置pq环境变量--')
            set_env_cmd = f"echo 'export {self.pq_env_name}={pq_lib_path}' " \
                          f">> {macro.DB_ENV_PATH}"
            try:
                result = pri_dbuser.sh(set_env_cmd).result()
                log.info(f"{pri_dbuser.name} 执行结果: {result}")
                results.append(result)
            except Exception as e:
                log.error(f"{pri_dbuser.name} 执行异常: {str(e)}")
                results.append(f"ERROR: {str(e)}")
        check_env_result = pri_dbuser.sh(check_env_cmd).result()
        log.info(check_env_result)
        self.assertEqual(check_env_result, 'True', '执行失败:' + step_txt)

    def test_main(self):
        step_txt = '----step0:查看config_file配置值;----'
        log.info(step_txt)
        self.conf_file = self.com.show_param("config_file")
        self.conf_file_bak = self.conf_file + '_gsc0007'

        step_txt = '----step0:查看enable_pq初始配置值;----'
        log.info(step_txt)
        self.init_para = self.com.show_param("enable_pq")

        step_txt = '----step1:guc修改enable_pq为数字2; expect:失败----'
        log.info(step_txt)
        msg = self.sh.execute_gsguc('set',
                                    self.constant.GSGUC_SUCCESS_MSG,
                                    f"enable_pq= 2")
        self.assertFalse(msg, '执行失败:' + step_txt)

        step_txt = '----step2:guc修改enable_pq为字符类型; expect:失败----'
        log.info(step_txt)
        msg = self.sh.execute_gsguc('set',
                                    self.constant.GSGUC_SUCCESS_MSG,
                                    f"enable_pq= test")
        self.assertFalse(msg, '执行失败:' + step_txt)

        step_txt = '----step3:guc修改enable_pq为空; expect:失败----'
        log.info(step_txt)
        msg = self.sh.execute_gsguc('set',
                                    self.constant.GSGUC_SUCCESS_MSG,
                                    f"enable_pq= ")
        self.assertFalse(msg, '执行失败:' + step_txt)

        step_txt = '----step4:alter system方式修改enable_pq为数字2; ' \
                   'expect:失败----'
        log.info(step_txt)
        alter_sql = 'alter system set enable_pq to 2;'
        result = self.sh.execut_db_sql(alter_sql)
        log.info(result)
        err_flag = 'ERROR:  parameter "enable_pq" requires a ' \
                   'Boolean value'
        self.assertIn(err_flag, result, '执行失败:' + step_txt)

        step_txt = '----step5:修改postgresql.conf文件参数为空，重启数据库; ' \
                   'expect:重启失败----'
        log.info(step_txt)
        shell_cmd = f"cp {self.conf_file} {self.conf_file_bak} &&" \
                    f"sed -i '$a enable_pq=' {self.conf_file}"
        log.info(shell_cmd)
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        shell_cmd = f"grep -n 'enable_pq' {self.conf_file}"
        log.info(shell_cmd)
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        row_nu = shell_result.splitlines()[-1].split(':')[0].strip()
        step_txt = '----step5:修改参数为空，重启数据库; expect:重启失败----'
        log.info(step_txt)
        self.sh.stop_db_instance()
        start_result = self.sh.start_db_instance()
        err_flag = f'syntax error in file "{self.conf_file}" line {row_nu}'
        self.assertIn(err_flag, start_result, '执行失败:' + step_txt)

        step_txt = '----step6:修改postgresql.conf文件参数为非法值，重启数据库; ' \
                   'expect:重启失败----'
        log.info(step_txt)
        shell_cmd = f"cp {self.conf_file_bak} {self.conf_file} &&" \
                    f"sed -i '$a enable_pq=123' {self.conf_file}"
        log.info(shell_cmd)
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        shell_cmd = f"grep -n 'enable_pq' {self.conf_file}"
        log.info(shell_cmd)
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        step_txt = '----step6:修改参数为非法值，重启数据库; expect:重启失败----'
        log.info(step_txt)
        self.sh.stop_db_instance()
        start_result = self.sh.start_db_instance()
        err_flag = '"enable_pq" requires a Boolean value'
        self.assertIn(err_flag, start_result, '执行失败:' + step_txt)

    def tearDown(self):
        step_txt = '----this is teardown----'
        log.info(step_txt)
        step1_txt = '----还原postgresql.conf文件，重启数据库; ' \
                    'expect:重启成功----'
        log.info(step1_txt)
        shell_cmd = f"cp {self.conf_file_bak} {self.conf_file} &&" \
                    f"rm -rf {self.conf_file_bak}"
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        shell_cmd = f"grep -n 'enable_pq' {self.conf_file}"
        log.info(shell_cmd)
        shell_result = pri_dbuser.sh(shell_cmd).result()
        log.info(shell_result)
        self.sh.stop_db_instance()
        start_result = self.sh.start_db_instance()
        step2_txt = '----查询数据库状态; expect:状态正常----'
        log.info(step2_txt)
        status_result = self.sh.get_db_cluster_status('status')
        step3_txt = '----查询参数; expect:参数为初始值----'
        log.info(step3_txt)
        self.new_para = self.com.show_param("enable_pq")

        log.info(f'----{os.path.basename(__file__)}:end----')
        self.assertTrue(start_result, '执行失败:' + step_txt + step1_txt)
        self.assertTrue(status_result, '执行失败:' + step_txt + step2_txt)
        self.assertEqual(self.new_para, self.init_para,
                         '执行失败:' + step_txt + step3_txt)
